const LogModel = require('../../model/Log');
const moment = require('moment')
const Dish = require('../../model/Dish')

module.exports = {

    changeDish: async(req, res, next) => {
        try {
            if (req.body.id) {
                let dish = await Dish.findOne({ _id: req.body.id }).exec()
                dish.store = req.body.store,
                    dish.title = req.body.title,
                    dish.subtitle = req.body.subtitle,
                    dish.updatedAt = new Date(),
                    dish.images = req.body.images
                dish.detail = req.body.detail
                dish.imageUrl = req.body.imageUrl
                await dish.save()
                return res.ok('修改菜品成功', dish)
            } else if (!req.body.id) {
                let newDish = new Dish({
                    store: req.body.store,
                    title: req.body.title,
                    subtitle: req.body.subtitle,
                    updatedAt: new Date(),
                    images: req.body.images,
                    detail: req.body.detail,
                    isDelete: 0,
                    imageUrl: req.body.imageUrl
                })
                await newDish.save()
                return res.ok('创建菜品成功', newDish)
            }
        } catch (e) {
            next(e)
        }
    },


    deleteDish: async(req, res, next) => {
        try {
            let dish = await Dish.findOne({ _id: req.body.id }).exec()
            dish.isDelete = 1
            await dish.save()
            return res.ok('删除菜品成功')
        } catch (e) {
            next(e)
        }
    },


    getOneDish: async(req, res, next) => {
        try {
            let dish = await Dish.findOne({ _id: req.body.id, isDelete: 0 }).populate('store').exec()
            return res.ok('查询菜品成功', dish)
        } catch (e) {
            next(e)
        }
    },

    getDishList: async(req, res, next) => {
        try {
            let option = {}
            option.isDelete = 0
            if (req.body.name) {
                option.title = new RegExp(req.body.name, 'i')
            }
            if (req.body.isDelete) {
                option.isDelete = req.body.isDelete
            }
            let count = await Dish.countDocuments(option).exec()
            let page = req.body.page || 1
            let pageSize = req.body.pageSize || count
            let data = await Dish.find(option).skip((page - 1) * pageSize).limit(pageSize).exec()
            let result = {}
            result.total = count
            result.currentPage = page
            result.data = data
            result.pageSize = pageSize
            return res.ok('获取列表成功', result)
        } catch (e) {
            next(e)
        }
    }

};